package com.etong.citymap.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;

import com.etong.citymap.util.log.LogUtil;

public class AsyncImageLoader {
	private Map<String, Drawable> imgCachMap;
	
	public AsyncImageLoader()
	{
		imgCachMap=new HashMap<String, Drawable>();
	}
	
	public Drawable loaDrawable(final String imgUrl,final ImageCallback imageCallback){
		if(imgCachMap.containsKey(imgUrl))
		{
			Drawable drawable=imgCachMap.get(imgUrl);
			if(drawable!=null)
			{
				return drawable;
			}
		}
		
		final Handler handler=new Handler(){

			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				imageCallback.imageLoaded((Drawable)msg.obj, imgUrl);
			}
		};
		
		new Thread(){

			@Override
			public void run() {
				super.run();
				Drawable drawable=loadImageFromUrl(imgUrl);
				imgCachMap.put(imgUrl, drawable);
				Message message = handler.obtainMessage(0, drawable);
                handler.sendMessage(message);
			}
		}.start();
		
		return null;
		
	};
	
		public static Drawable loadImageFromUrl(String url) {
			URL m;
			InputStream i = null;
			try {
				m = new URL(url);
				i = (InputStream) m.getContent();
			} catch (MalformedURLException e1) {
				e1.printStackTrace();
			} catch (IOException e) {
				LogUtil.e(e);
			}
			Drawable d = Drawable.createFromStream(i, "src");
			return d;
		}
		
    public interface ImageCallback {
        public void imageLoaded(Drawable imageDrawable, String imageUrl);
    }
}
